<?php
require_once( dirname(__FILE__).'/../libs/bedmintonlib.php' );

function randomString( $length ) 
{
    $validCharacters = "abcdefghijklmnopqrstuxyvwzABCDEFGHIJKLMNOPQRSTUXYVWZ";
    $validCharNumber = strlen($validCharacters);
 
    $result = "";
 
    for ($i = 0; $i < $length; $i++) {
        $index = mt_rand(0, $validCharNumber - 1);
        $result .= $validCharacters[$index];
    }
 
    return $result;
}

function sendPassword( $login, $english, & $outMessage )
{
    $iniReader = new IniReader();
    if (!$iniReader->iniValue( "smtpHost", $smtpHost ) ||
        !$iniReader->iniValue( "addressFromRegistracia", $addressFromRegistracia ) ||
        !$iniReader->iniValue( "addressRegistraciaPassword", $addressRegistraciaPassword ))
    {
        $outMessage = "Failed to read ini value";
        return false;
    }
    
    $db = Db::db();
    $dbConnection = $db->connection();
    if (is_null( $dbConnection ))
    {
        $outMessage = $db->getErrorStr();
        return false;
    }

    try
    {
        $statement = $dbConnection->prepare( "SELECT 1 FROM customers WHERE emailaddress = ?");
        $statement->bindParam( 1, $login, PDO::PARAM_STR );
        $statement->execute();
        $obj = $statement->fetch( PDO::FETCH_OBJ );
        if (! $obj)
        {
            $outMessage = $english ? "Login not exists for the user" : "Tento email nebol zaregistrovaný";
            return false;
        }
        
        $newPassword = randomString( 8 );
        $statement = $dbConnection->prepare( "UPDATE customers SET passwordtochange  = ? WHERE emailaddress = ?");
        $statement->bindParam( 1, $newPassword, PDO::PARAM_STR );
        $statement->bindParam( 2, $login, PDO::PARAM_STR );
        $statement->execute();
        
       /* $headersStr = "MIME-Version: 1.0\r\nFrom: Registrácia <registracia@bedminton.com>\r\n";*/
        $subjectStr = "Nové heslo";
        $from =  "Registrácia BBC";
        $to = "Vážený zákazník";
        $bodyStr = "Systém vygeneroval nové heslo. Toto heslo si môžete kedykoľvek zmeniť. Novovygenerované heslo je: $newPassword";
        if ($english)
        {
            $from =  "Registration BBC";
            $to = "Dear customer";
            $subjectStr = "New password";
            $bodyStr = "The system has generated new password. This password you can change at any time. New generated password is: $newPassword";
        }
        
        // uprav data
        $mail = new PHPMailer( true );
        $mail->IsSMTP();
        $mail->CharSet    = "UTF-8";
        $mail->Host       = $smtpHost; 
        $mail->SMTPAuth   = true;                  
        $mail->Port       = 25;                    
        $mail->Username   = $addressFromRegistracia; 
        $mail->Password   = $addressRegistraciaPassword;        
        $mail->AddAddress( $login, $to );
        $mail->SetFrom( $addressFromRegistracia, $from );
        $mail->Subject = $subjectStr;
        $mail->Body = $bodyStr;
        $mail->Send();

        $db->commit();
        WebStat::logForgottenPassword( $login );
        logInfo( "Password changed", LOG_INFO_PASSWORD_CHANGED );
    }
    catch(PDOException $e)
    {
        $outMessage = $e->getMessage();
        return false;
    }
    catch (phpmailerException $e)
    {
        $outMessage = $e->errorMessage();
        logError( __FUNCTION__ . ": Unable to send mail $outMessage" );
        return false;
    }
    catch (Exception $e)
    {
        $outMessage = $e->getMessage();
        logError( __FUNCTION__ . ": Unable to send mail $outMessage" );
        return false;
    }
    
    return true;
}

if (! isset( $_POST['emailaddress'] ))
    exit;

$english = isEnglish();
if (! sendPassword( $_POST['emailaddress'], $english, $outMessage ))
{
    showError( $outMessage );
    exit;
}

$echoStr = "Na vašu emailovú adresu bolo poslané novovygenerované heslo, ktoré si môžete zmeniť v sekcii Prihlásenie";
if ($english)
{
    $echoStr = "There was sent an email to your email address with new generated password. This password you can change in login section"; 
}

showInfo( $echoStr )

?>
